import { defineStore } from "pinia";
import { reactive } from "vue";
import router, { constantRoutes, dynamicRoutes } from '@/router';
import Layout from "@/Layout/Layout";
import ParentView from '@/components/ParentView/index';
import auth from '@/common/plugins/auth.js';
import to from "await-to-js";
import { useStore as useUserStore } from "@/store/user";
import useRequest from "@/common/hooks/useRequest";
import { message } from "ant-design-vue";
export const useStore = defineStore('router', () => {
  const state: any = reactive({
    pulled: false,
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  })

  // 遍历后台传来的路由字符串，转换为组件对象
  const filterAsyncRouter = (asyncRouterMap, lastRouter = false, type = false) => {
    return asyncRouterMap.filter(route => {
      // if (type && route.children) {
      //   route.children = filterChildren(route.children)
      // }
      // type=1的需要重定向，没有redirect字段的默认取子路由第一项
      if (route?.meta?.type === "1") {
        if (!route?.redirect && route?.children?.length > 0) {
          route.redirect = {
            name: route?.children?.[0]?.name,
          };
        }
      }
      if (route?.component) {
        // Layout ParentView 组件特殊处理
        if (route.component === 'Layout') {
          route.component = Layout;
        } else if (route.component === 'ParentView') {
          route.component = ParentView;
        } else {
          route.component = loadView(route.component);
        }
      }
      if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, route, type)
      } else {
        delete route['children']
        delete route['redirect']
      }
      return true
    })
  }

  const filterChildren = (childrenMap, lastRouter?: any) => {
    let children: any[] = [];
    childrenMap.forEach((el, index) => {
      if (el.children && el.children.length) {
        if (el.component === 'ParentView' && !lastRouter) {
          el.children.forEach(c => {
            c.path = el.path + '/' + c.path
            if (c.children && c.children.length) {
              children = children.concat(filterChildren(c.children, c))
              return
            }
            children.push(c)
          })
          return
        }
      }
      if (lastRouter) {
        el.path = lastRouter.path + '/' + el.path
        if (el.children && el.children.length) {
          children = children.concat(filterChildren(el.children, el))
          return
        }
      }
      children = children.concat(el)
    })
    return children
  }

  const SET_ROUTES = (routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  }
  const SET_DEFAULT_ROUTES = (routes) => {
    state.defaultRoutes = constantRoutes.concat(routes);
  }
  const SET_TOPBAR_ROUTES = (routes) => {
    state.topbarRouters = routes;
  }
  const SET_SIDEBAR_ROUTERS = (routes) => {
    state.sidebarRouters = routes;
  }

  // 拉取动态路由
  const GenerateRoutes = async () => {
    const userStore = useUserStore();
    const requestHooks = useRequest();
    const axios = new requestHooks.Axios(process.env.VUE_APP_LOGIN_API);
    axios.setDatas({
      applicationId: '497229972428029952',
    })
    axios.setParams({
      applicationId: '497229972428029952',
    })
    axios.setHeaders({
      Authorization: 'Bearer ' + userStore.info.token,
    })
    let options: any = axios.getOptions();
    const [err, Mres]: any = await to(axios.fetchSimple('getMenu', options));
    if (err) {
      message.error(err.msg);
      return false;
    }
    const mRoutes = formatRoutes(Mres.data.data);
    const sdata = JSON.parse(JSON.stringify(mRoutes));
    const rdata = JSON.parse(JSON.stringify(mRoutes));
    const sidebarRoutes = filterAsyncRouter(sdata);
    const rewriteRoutes = filterAsyncRouter(rdata, false, true);
    const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
    rewriteRoutes.push({ path: '/:pathMatch(.*)*', redirect: '/404', hidden: true });
    asyncRoutes.forEach(x => {
      router.addRoute(x);
    })
    SET_ROUTES(rewriteRoutes);
    SET_SIDEBAR_ROUTERS(constantRoutes.concat(sidebarRoutes));
    SET_DEFAULT_ROUTES(sidebarRoutes);
    SET_TOPBAR_ROUTES(sidebarRoutes);
    return rewriteRoutes;
  }
  return {
    state,
    GenerateRoutes,
  }
})

//路由匹配字段
const formatRoutes = (routes) => {
  const routesEach = (e) => {
    let res: any[] = [];
    e.forEach(x => {
      if (["0", "1"].includes(x.menuType) || x.meta?.buttonRefer === 1) {
        let obj: any = {
          name: x.routerName,
          path: x.path,
          component: x.componentPath,
          hidden: false,
          meta: {
            icon: x.meta.icon,
            noCache: false,
            title: x.meta.title,
            type: x.menuType,
          }
        }
        if (x.children && x.children.length > 0) {
          obj.children = x.children;
          obj.children = routesEach(obj.children);
        }
        res.push(obj);
      }
    })
    return res;
  }
  routes = routesEach(routes);
  return routes;
}

export const loadView = (view) => {
  return () => import(`@/views/${view}`);
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res: any[] = [];
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}